package com.hmall.user.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmall.common.ThreadLocalUtil;
import com.hmall.user.mapper.AddressMapper;
import com.hmall.user.mapper.UserMapper;
import com.hmall.user.pojo.Address;
import com.hmall.user.pojo.User;
import com.hmall.user.service.UserService;
import org.apache.commons.lang.StringUtils;
import org.aspectj.weaver.ast.Var;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private AddressMapper addressMapper;

    /**
     * 根据用户id查询地址列表
     *
     * @param uid
     * @return
     */
    @Override
    public List<Address> findAddressByUserId(Long uid) {
//        if (StringUtils.isNotBlank(uid.toString())) {
            List<Address> addressList = addressMapper.findAddressByUserId(uid);
            return addressList;
//        } else {
//            throw new RuntimeException();
//        }
    }

    /**
     * 根据地址id查找地址
     *
     * @param addressId
     * @return
     */
    @Override
    public Address findAddressByAddressId(String addressId) {
        if (StringUtils.isNotBlank(addressId)) {
            Address address = addressMapper.findAddressByAddressId(Long.valueOf(addressId));
            return address;
        } else {
            throw new RuntimeException();
        }
    }

    @Override
    public User findUserByUserId(Long userId) {
        User user = userMapper.findUserByUserId(userId);
        return user;
    }

    /**
     * 修改账户余额
     * @param totalFee
     */
    @Override
    public void updateBalance(Long totalFee) {
        Long userId = ThreadLocalUtil.getUserId();
        User user = userMapper.findUserByUserId(userId);
        Long balance = user.getBalance() - totalFee ;
        userMapper.updateBalanceByUserId(userId,balance);
    }


}
